const canvas = document.getElementById("banner");
const obstacles = [];
let lastObstacleTime = 0;
const obstacleInterval = 1000; // 障碍物生成间隔，单位：毫秒
const obstacleSpeed = 5; // 障碍物移动速度，单位：像素/帧
const obstacleWidth = 50; // 障碍物宽度，单位：像素
const obstacleHeight = 50; // 障碍物高度，单位：像素
let lastHurtTime = 0;

// 生成随机位置
function getRandomPosition() {
  const obstacleRightEdge = canvas.offsetWidth - obstacleWidth; // 障碍物右边缘的位置
  const minRightX = obstacleRightEdge - 100; // 设置障碍物在画布右侧的最小x坐标（例如，距离右边缘100px）
  const randomX =
    Math.floor(Math.random() * (obstacleRightEdge - minRightX)) + minRightX; // 在右侧范围内生成随机x坐标
  const randomY = Math.floor(
    Math.random() * (canvas.offsetHeight - obstacleHeight)
  ); // 生成随机y坐标
  return { x: randomX, y: randomY };
}

// 创建障碍物
function createObstacle() {
  console.log("生成");
  const position = getRandomPosition();
  const obstacle = document.createElement("div");
  obstacle.className = "obstacle";
  obstacle.style.left = `${position.x}px`;
  obstacle.style.top = `${position.y}px`;
  obstacle.style.backgroundImage = `url('./img/障碍物.png')`; // 替换图片的URL
  obstacle.style.backgroundSize = "cover";
  canvas.appendChild(obstacle);
  obstacles.push(obstacle);
  // 死亡时候清除后面生成障碍物
  if (healthy[0].style.display == "none") {
    obstacle.style.display = "none";
  }
}
const creatTimer = setInterval(createObstacle, 1000);

// 更新障碍物位置
function updateObstacles() {
  obstacles.forEach((obstacle) => {
    obstacle.style.left = `${parseInt(obstacle.style.left, 10) - obstacleSpeed
      }px`;
    if (parseInt(obstacle.style.left, 10) + obstacleWidth < -500) {
      canvas.removeChild(obstacle);
      obstacles.splice(obstacles.indexOf(obstacle), 1);
    }
  });
}
const speedTimer = setInterval(updateObstacles, 20);


// let isStart = false;
// 暂停
function stopgame() {
  var btnstop = document.getElementById("btnstop");
  btnstop.style.display = "block";
  console.log(1, creatTimer, speedTimer);
  //   isStart = false;
  clearInterval(creatTimer);
  clearInterval(speedTimer);
  clearInterval(gameStart);//暂停倒计时
  cancelAnimationFrame(animationId)
}
//计时器
let timer = 20
let choice0 = document.getElementsByClassName("choice0")
function timeStart() {
    timer--
    choice0[0].innerHTML = "距离胜利还有  " + timer + "  秒" 
    if (timer == 0 || healthy[0].style.display == "none") {
        choice0[0].style.display = "none"
    }

}
let gameStart = setInterval(timeStart,1000)
document.getElementsByClassName("continue")[0].addEventListener("click", function(){
    gameStart = setInterval(timeStart,1000)
})


//检测生命
//获取人物图源
let dinoFace = document.querySelector("#dino>img");
//设置图源
let painFell = function () {
  //   painSound.play();
};
let dieFace = "xiao/动2.png";
let lifeFace = "./img/鬼.gif";
let painFace = "xiao/动3.gif";
//设置生命变化
let healthy = document.getElementsByTagName("li");
let lives = 3;
let hurtAnimation = "hurt 0.5s linear";
function updateLives() {
  const now = Date.now();
  // 检查当前时间与上一次减少生命值的时间差是否至少为1秒
  if (now - lastHurtTime > 1000) {
    lives--;
    lastHurtTime = now; // 更新上一次减少生命值的时间戳
  }
}
//受伤声音
let painSound = new Audio("xiao/吃痛.mp3");
// 死亡功能
function dieAppearance() {
  for (i = 0; i <= 2; i++) {
    choice[i].style.display = "block";
  }
}
//检测碰撞
function checkCollision() {
  const dino = document.getElementById("dino");
  const obstacles = document.getElementsByClassName("obstacle");
  for (let i = 0; i < obstacles.length; i++) {
    const obstacle = obstacles[i];
    const dinoRect = dino.getBoundingClientRect();
    const obstacleRect = obstacle.getBoundingClientRect();
    const padding = 20;
    // 检查碰撞
    if (
      dinoRect.right - padding > obstacleRect.left + padding &&
      dinoRect.left + padding < obstacleRect.right - padding &&
      dinoRect.bottom - padding > obstacleRect.top + padding &&
      dinoRect.top + padding < obstacleRect.bottom - padding
    ) {
      painFell();
      healthy[lives - 1].style.display = "none";
      dino.style.animation = hurtAnimation;
      dinoFace.src = painFace;
      let dieIf = healthy[0].style.display == "none";
      setTimeout(function () {
        updateLives();
        dino.style.animation = "none";
        dinoFace.src = lifeFace;
        if (dieIf) {
          //死亡效果
          dinoFace.style.display = "none";
          hurtAnimation = "none";
          dino.style.transform = "rotate(90deg)";
          die.style.transform = "translateY(100%)";
          dinoFace.src = dieFace;
          painFell = function () {
            lifeFace = dieFace;
            painFace = dieFace;
          };

          laugh.play();
          updateLives = function () {
            lives = 1;
          };
          commend = () => {
            return;
          };
          dieAppearance();
        }
      }, 500);

      // return; // 检测到碰撞后，退出循环
    }
  }
}
// 获取死亡结算界面
let die = document.querySelector("#banner>#die>img");
let nowStart = Date.now();
let commend = function () {
  const startCommend = new Audio("xiao/通关音效2_01.mp3");
  startCommend.play();
};
function victory() {
  const now = Date.now();
  if (timer == 0 && healthy[0].style.display != "none") {
    // 清空生命
    for (i = 0; i < 3; i++) {
      healthy[i].style.display = "none";
    }
    dinoFace.style.display = "none";
    choice[0].innerHTML = "恭喜，你胜利了！";
    die.style.transform = "translateY(100%)";
    dieAppearance();
    commend();

    bgSoundStart = function () {
      return;
    };
    commend = () => {
      return;
    };
  }
}
let animationId = 0;
// 游戏循环
function gameLoop() {
  console.log("gameloop");
  var btnstop = document.getElementById("btnstop");
  btnstop.style.display = "none";
  const now = Date.now();
  //   isStart = true; // 游戏开始状态设为true
  if (now - lastObstacleTime > obstacleInterval) {
    createObstacle();
    lastObstacleTime = now;
  }
  // setInterval
  updateObstacles();
  checkCollision(); // 在这里调用你的碰撞检测函数
  victory(); //调用胜利方法

  //   if (isStart)
  animationId = requestAnimationFrame(gameLoop);
}

// 开始游戏循环
gameLoop();
